package com.relax.condition;

/**
 * java方式实现三个线程轮流执行
 * 使用wait():方法要加 synchronized 和 notify():随机唤醒一个
 *
 */

public class NoUseConditionDemo {


    private int num = 0;

    public synchronized void a() {
        while (num != 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("a........");
        num++;
        notifyAll();
    }

    public synchronized void b() {
        while (num != 1) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("b........");
        num++;
        notifyAll();

    }

    public synchronized void c() {
        while (num != 2) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("c........");
        num = 0;
        notifyAll();

    }


    public static void main(String[] args) {
        final NoUseConditionDemo demo = new NoUseConditionDemo();

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    demo.a();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    demo.b();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    demo.c();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
